//
//  BIZContractEditVC.m
//  biz
//
//  Created by 小龙 on 2017/4/18.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "BIZContractEditVC.h"
#import "BIZConsultorListViewController.h"
#import "BIZConsultorDetailModel.h"
#import "BIZContractFileListVC.h"

@interface BIZContractEditVC ()<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *fileNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *uploadResultLabel;
@property (weak, nonatomic) IBOutlet BWHTextView *contentTextView;
@property (weak, nonatomic) IBOutlet UIView *consultBackView;
@property (weak, nonatomic) IBOutlet UILabel *consultNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *consultPosiationLabel;
@property (weak, nonatomic) IBOutlet UILabel *consultCompanyLabel;
@property (weak, nonatomic) IBOutlet UIImageView *consultHeadImageView;
@property (weak, nonatomic) IBOutlet UIView *backView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *consultBtnHeightLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *consultBtnTopLayout;
@property (weak, nonatomic) IBOutlet UIButton *upLoadBtn;
/*选择的咨询师id*/
@property (atomic, copy) NSString *cuserIdSelected;

/*真实文件名*/
@property (atomic, copy) NSString *realFileName;

/** 上传文件的路径 */
@property (nonatomic, copy) NSString *docFilePath;

@property (weak, nonatomic) IBOutlet UIButton *twoHoursBtn;

@property (weak, nonatomic) IBOutlet UIButton *oneDayBtn;
/** <#assign属性注释#> */
@property (nonatomic, assign) NSInteger timeBtnTagSelected;
@property (weak, nonatomic) IBOutlet UIView *ruleView;
@property (weak, nonatomic) IBOutlet UILabel *ruleLabel;

@end

@implementation BIZContractEditVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setupNavBar];
    
    [self setupUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadUI:) name:kGetChooseConsultModelNotification object:nil];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setupNavBar
{
    self.title = @"审合同";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClick)];
    
}

- (void)setupUI
{
    
    self.contentTextView.placeHolder = @"请输入您要提交审核合同的要求，您还可以输入300字......";
    self.contentTextView.placeHolderTextColor = HEXCOLOR(0xcccccc);
    
    self.backView.layer.shadowOpacity = 0.5;// 阴影透明度
    
    self.backView.layer.shadowColor = [UIColor lightGrayColor].CGColor;// 阴影的颜色
    
    self.backView.layer.shadowRadius = 3;// 阴影扩散的范围控制
    
    self.backView.layer.shadowOffset  = CGSizeMake(2, 2);// 阴影的范围
    
    self.uploadResultLabel.text = @"";
    
    self.timeBtnTagSelected = -1;
}


- (void)reloadUI:(NSNotification *)notification
{
    self.consultBackView.hidden = NO;
    
    BIZConsultorDetailModel *model = notification.userInfo[@"model"];
    self.consultNameLabel.text = model.cname;
    self.cuserIdSelected = model.uuid;
    [SDWebImageTool imageView:self.consultHeadImageView imageName:model.headImg placeHolder:@"default-head" showProgress:NO];
    self.consultCompanyLabel.text = model.fname;
    self.consultPosiationLabel.text = model.position;
    self.consultBtnTopLayout.constant = 0;
    self.consultBtnHeightLayout.constant = 0;
    // [self loadViewIfNeeded];
    
}



- (void)rightBarButtonItemClick
{
    
//    {
//        "content":"内容",
//        "cuserId":"33333305",
//        "originalFileName":"原文件名",
//        "realFileName":"sZE8iJsT",
//        "type":1
//    }
    
    if (!self.contentTextView.text.length) {
        [MBProgressHUD showTipMessageInWindow:@"请输入您的线下咨询要求"];
        return;
    }
    
    if (!self.cuserIdSelected.length) {
        [MBProgressHUD showTipMessageInWindow:@"请选择咨询师"];
        return;
    }
    
    if ([self.fileNameLabel.text isEqualToString:@"尚未选择任何文件"]) {
        [MBProgressHUD showTipMessageInWindow:@"尚未选择任何文件"];
        return;
    }
    
    
    if (!self.realFileName.length) {
        [MBProgressHUD showTipMessageInWindow:@"请点击上传文件"];
        return;
    }
    
    if (self.timeBtnTagSelected<0) {
        [MBProgressHUD showTipMessageInWindow:@"请点击选择接单时效"];
        return;
    }
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"content"] = self.contentTextView.text;
    dic[@"cuserId"] = self.cuserIdSelected;
    dic[@"originalFileName"] =  self.fileNameLabel.text;
    dic[@"realFileName"] = self.realFileName;
    dic[@"type"] = @(self.timeBtnTagSelected);
    
    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kCommitContractUrl parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"responseObject+++++:%@",responseObject);
        [MBProgressHUD  hideHUD];
        if ([responseObject[@"code"] integerValue] == 1) {
            if (self.commitContractReturnBlock) {
                self.commitContractReturnBlock();
            }
            
           
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [MBProgressHUD showErrorMessage:responseObject[@"des"]];
            if ([responseObject[@"des"] integerValue] == 2) {
                BIZLoginViewController *vc = [BIZLoginViewController viewControllerFromStoryboard];
                [self presentViewController:vc animated:YES completion:nil];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error+++++:%@",error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
    }];

}

- (IBAction)chooseFileBtnClick {
    
    BIZContractFileListVC *vc = [[BIZContractFileListVC alloc]init];
    BIZNavigationController *nav = [[BIZNavigationController alloc]initWithRootViewController:vc];
    
    MPWeakSelf(self);
    vc.selecteFileReturnBlock = ^(NSString *docFilePath){
        NSArray *array = [docFilePath componentsSeparatedByString:@"/"];
        weakself.fileNameLabel.text = [array lastObject];
        weakself.docFilePath = docFilePath;
        weakself.upLoadBtn.enabled = YES;
        weakself.upLoadBtn.layer.borderColor = HEXCOLOR(0x2E8CE5).CGColor;
        [weakself.upLoadBtn setTitleColor:HEXCOLOR(0x2E8CE5) forState:UIControlStateNormal];
    };
    [self presentViewController:nav animated:YES completion:nil];
}



- (IBAction)uploadFileBtnClick {
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"file"] = [NSData dataWithContentsOfFile:self.docFilePath];
    [MBProgressHUD showAnimationHUD];
    
    [RequestTool postFile:kUploadUrl parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

         [formData appendPartWithFileURL:[NSURL fileURLWithPath:self.docFilePath] name:@"file" error:nil];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {

        NSLog(@"%f",1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        // 回到主队列刷新UI,用户自定义的进度条
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD showProgressWithMessage:@"上传中" progress:1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount];
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        DeLog(@"responseObject+++++:%@",responseObject);
        [MBProgressHUD  hideHUD];
        
        if ([responseObject[@"code"] integerValue] == 1) {
            [MBProgressHUD showSuccessMessage:responseObject[@"des"]];
            self.uploadResultLabel.text = @"已上传完毕";
            self.realFileName = responseObject[@"data"];
            self.upLoadBtn.enabled = YES;
            self.upLoadBtn.layer.borderColor = HEXCOLOR(0x999999).CGColor;
            [self.upLoadBtn setTitleColor:HEXCOLOR(0x999999) forState:UIControlStateNormal];
        }else {
            [MBProgressHUD showErrorMessage:responseObject[@"des"]];
            if ([responseObject[@"des"] integerValue] == 2) {
                BIZLoginViewController *vc = [BIZLoginViewController viewControllerFromStoryboard];
                [self presentViewController:vc animated:YES completion:nil];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error+++++:%@",error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
    }];
    
    
}

- (IBAction)chooseConsultBtnClick {

    BIZConsultorListViewController *vc = [[BIZConsultorListViewController alloc] initWithType:BIZConsultorListViewControllerTypeFromContract];
    [self.navigationController pushViewController:vc animated:YES];
}


-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

- (IBAction)selectTimeBtnClick:(UIButton *)sender {
    
    self.ruleView.hidden = NO;
    if (sender.tag == 1000) {
        [self.oneDayBtn setTitleColor:HEXCOLOR(0x2E8CE5) forState:UIControlStateNormal];
        self.oneDayBtn.layer.borderColor = HEXCOLOR(0x2E8CE5).CGColor;
        [self.twoHoursBtn setTitleColor:HEXCOLOR(0x999999) forState:UIControlStateNormal];
        self.twoHoursBtn.layer.borderColor = HEXCOLOR(0x999999).CGColor;
        self.ruleLabel.text = @"24小时内接单：您的合同审核要求在发布的24小时内会有咨询师接单，如果在24小时内咨询师没有接单，则合同审核次数不会被扣除。";
    }
    else {
        [self.oneDayBtn setTitleColor:HEXCOLOR(0x999999) forState:UIControlStateNormal];
        self.oneDayBtn.layer.borderColor = HEXCOLOR(0x999999).CGColor;
        [self.twoHoursBtn setTitleColor:HEXCOLOR(0x2E8CE5) forState:UIControlStateNormal];
        self.twoHoursBtn.layer.borderColor = HEXCOLOR(0x2E8CE5).CGColor;
        self.ruleLabel.text = @"2小时内接单：您的合同审核要求在发布的2小时内会有咨询师接单，如果在2小时内咨询师没有接单，则合同审核次数不会被扣除。";
    }
    
    self.timeBtnTagSelected = sender.tag-1000;
    
}


@end
